package com.hitfm.iplay.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.hitfm.iplay.MusicInfoController;
import com.hitfm.iplay.MusicPlayerApp;
import com.hitfm.iplay.MusicPlayerService;
import com.hitfm.iplay.R;
import com.hitfm.iplay.ui.VerticalSeekBar;
import com.hitfm.iplay.util.ChangeGradation;
import com.hitfm.iplay.util.ConvertTime;

public class PlayingActivity extends Activity {
	private MusicPlayerService mMusicPlayerService = null;
	private MusicInfoController mMusicInfoController = null;
	private String song_name;
	private String song_singer;
	private Cursor mCursor = null;
	private MusicPlayerApp musicPlayerApp;
	private ServiceConnection mPlaybackConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			mMusicPlayerService = ((MusicPlayerService.LocalBinder) service)
					.getService();
		}

		public void onServiceDisconnected(ComponentName className) {
			mMusicPlayerService = null;
		}
	};
	private TextView playing_name;
	private ImageView playing_status;
	private ImageView playing_pre;
	private ImageView playing_next;
	private com.hitfm.iplay.ui.VerticalSeekBar playing_vol_seekbar;
	private ImageView playing_vol;
	private ImageView playing_random;
	private ImageView albumart;
	private Handler mHandler = new Handler();
	private AudioManager mAudioManager;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.playing);
		findViews();
		initService();
		setListners();
	}

	Runnable seekbarThread = new Runnable() {
		// 将要执行的操作写在线程对象的run方法当中
		public void run() {
			playing_vol_seekbar.setVisibility(View.INVISIBLE);
			mHandler.removeCallbacks(seekbarThread);
		};
	};

	Runnable playProgressThread = new Runnable() {
		// update the playing_seekber's progress and the text of song time
		public void run() {
			if (isPlayingSeekbarTouch) {
				return;
			}
			int position = mMusicPlayerService.getPosition();
			int duration = mMusicPlayerService.getDuration();
			int progress = (position * playing_seekbar.getMax()) / duration;
			playing_progress.setText(ConvertTime
					.milliToSecs(mMusicPlayerService.getPosition()));
			playing_total_time.setText(ConvertTime
					.milliToSecs(mMusicPlayerService.getDuration()));
			playing_seekbar.setProgress(progress);
			mHandler.postDelayed(playProgressThread, 1000);
		};
	};

	private TextView playing_total_time;
	private TextView playing_progress;
	// private ProgressBar playing_progressbar;
	private android.widget.SeekBar playing_seekbar;
	protected boolean isPlayingSeekbarTouch = false;

	private void setListners() {
		playing_status.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mMusicPlayerService.isPlaying()) {
					mMusicPlayerService.pause();
				} else if (null == mMusicPlayerService.getMusicPath()
						&& !mMusicPlayerService.isPlaying()) {
					mMusicPlayerService.nextOrPreSong(true);
				} else {
					mMusicPlayerService.start();
				}
			}
		});
		playing_next.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mMusicPlayerService.isPlaying()
						|| mMusicPlayerService.isPaused()) {
					mMusicPlayerService.nextOrPreSong(true);
				}
			}
		});
		playing_pre.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mMusicPlayerService.isPlaying()
						|| mMusicPlayerService.isPaused()) {
					mMusicPlayerService.nextOrPreSong(false);
				}
			}
		});
		playing_random.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (null != mMusicPlayerService) {
					mMusicPlayerService.setRandom(!mMusicPlayerService
							.isRandom());
				}
				setRandomGradation();
			}
		});
		playing_vol.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// playing_vol_seekbar.setThumb(getResources().getDrawable(R.drawable.playprocess_thumb));
				playing_vol_seekbar.setProgress(mAudioManager
						.getStreamVolume(AudioManager.STREAM_MUSIC)
						* 100
						/ mAudioManager
								.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
				playing_vol_seekbar
						.setVisibility((View.VISIBLE == playing_vol_seekbar
								.getVisibility()) ? View.INVISIBLE
								: View.VISIBLE);
				mHandler.postDelayed(seekbarThread, 3000);
			}
		});
		playing_vol_seekbar
				.setOnSeekBarChangeListener(new com.hitfm.iplay.ui.VerticalSeekBar.OnSeekBarChangeListener() {

					@Override
					public void onStopTrackingTouch(
							VerticalSeekBar VerticalSeekBar) {
						mHandler.postDelayed(seekbarThread, 3000);
					}

					@Override
					public void onStartTrackingTouch(
							VerticalSeekBar VerticalSeekBar) {
						mHandler.removeCallbacks(seekbarThread);
						Log.e("test", "start");
					}

					@Override
					public void onProgressChanged(
							VerticalSeekBar VerticalSeekBar, int progress,
							boolean fromUser) {
						int max = mAudioManager
								.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
						int index = playing_vol_seekbar.getProgress() * max
								/ playing_vol_seekbar.getMax();
						mAudioManager.setStreamVolume(
								AudioManager.STREAM_MUSIC, index,
								AudioManager.FLAG_PLAY_SOUND);
					}
				});
		playing_seekbar
				.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
					// 一次用户更改行为,依次执行start(),changed(),stop();
					int progress = 0;
					boolean fromUser = false;

					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {
						if (fromUser && mMusicPlayerService.isPlaying()) {
							int duration = mMusicPlayerService.getDuration();
							int max = playing_seekbar.getMax();
							int position = (duration * progress) / max;
							mMusicPlayerService.setPosition(position);
						}
						isPlayingSeekbarTouch = false;
					}

					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {
						isPlayingSeekbarTouch = true;
					}

					@Override
					public void onProgressChanged(SeekBar seekBar,
							int progress, boolean fromUser) {
						this.fromUser = fromUser;
						this.progress = progress;
					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		setRandomGradation();
	}

	private void setRandomGradation() {
		if (null != mMusicPlayerService && mMusicPlayerService.isRandom()) {
			playing_random.setImageDrawable(getResources().getDrawable(
					R.drawable.random));
		} else {
			playing_random.setImageDrawable(new ChangeGradation()
					.getChangeGradation(getResources().getDrawable(
							R.drawable.random)));
		}
	}

	private void findViews() {
		playing_name = (TextView) findViewById(R.id.playing_name);
		playing_status = (ImageView) findViewById(R.id.playing_status);
		playing_next = (ImageView) findViewById(R.id.playing_next);
		playing_pre = (ImageView) findViewById(R.id.playing_pre);
		playing_random = (ImageView) findViewById(R.id.playing_random);
		playing_vol = (ImageView) findViewById(R.id.playing_vol);
		playing_vol_seekbar = (com.hitfm.iplay.ui.VerticalSeekBar) findViewById(R.id.playing_vol_seekbar);
		playing_progress = (TextView) findViewById(R.id.playing_progress);
		playing_total_time = (TextView) findViewById(R.id.playing_total_time);
		// playing_progressbar = (ProgressBar)
		// findViewById(R.id.playing_progressbar);
		// playing_progressbar.setMax(1000);
		playing_seekbar = (android.widget.SeekBar) findViewById(R.id.playing_seekBar);
		playing_seekbar.setMax(1000);
		playing_seekbar.setThumb(getResources().getDrawable(
				R.drawable.playprocess_thumb));
		albumart = (ImageView) findViewById(R.id.albumart);
	}

	protected BroadcastReceiver mPlayerEvtReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MusicPlayerService.PLAYER_PREPARE_END)
					|| action.equals(MusicPlayerService.PLAY_CONTINUE)) {
				if (null == musicPlayerApp.getCursor()) {
					musicPlayerApp.initCursor();
				}
				mCursor = musicPlayerApp.getCursor();
				mCursor.moveToPosition(mMusicPlayerService.getId());
				song_name = mCursor.getString(mCursor
						.getColumnIndex(MediaStore.Audio.Media.TITLE));
				song_singer = mCursor.getString(mCursor
						.getColumnIndex(MediaStore.Audio.Media.ARTIST));
				playing_name.setText(song_singer + "-" + song_name);
				playing_name.setTextColor(0xFF9370DB);
				playing_status.setImageDrawable(PlayingActivity.this
						.getResources().getDrawable(R.drawable.pause));
				Bitmap albumImage = mMusicPlayerService.getAlbumArt();
				if (null != albumImage) {
					albumart.setImageBitmap(albumImage);
				} else {
					albumart.setImageResource(R.drawable.default_song_img);
				}
				mHandler.postDelayed(playProgressThread, 1000);
			} else if (action.equals(MusicPlayerService.PLAY_COMPLETED)) {
				playing_name.setText(R.string.playing);
				playing_name.setTextColor(getResources()
						.getColor(R.color.white));
				playing_status.setImageDrawable(PlayingActivity.this
						.getResources().getDrawable(R.drawable.play));
				mMusicPlayerService.nextOrPreSong(mMusicPlayerService
						.isRandom());
				mHandler.removeCallbacks(seekbarThread);
			} else if (action.equals(MusicPlayerService.PLAY_PAUSE)) {
				playing_status.setImageDrawable(PlayingActivity.this
						.getResources().getDrawable(R.drawable.play));
			} else if (action.endsWith(MusicPlayerService.ERROR)) {
				mHandler.removeCallbacks(seekbarThread);
				mHandler.removeCallbacks(playProgressThread);
				playing_status.setImageResource(R.drawable.play);
			}
		}
	};

	protected void initService() {
		musicPlayerApp = (MusicPlayerApp) getApplication();
		mMusicInfoController = musicPlayerApp.getMusicInfoController();

		startService(new Intent(this, MusicPlayerService.class));
		getApplicationContext().bindService(
				new Intent(this, MusicPlayerService.class),
				mPlaybackConnection, Context.BIND_AUTO_CREATE);

		IntentFilter filter = new IntentFilter();
		filter.addAction(MusicPlayerService.PLAYER_PREPARE_END);
		filter.addAction(MusicPlayerService.PLAY_COMPLETED);
		filter.addAction(MusicPlayerService.PLAY_PAUSE);
		filter.addAction(MusicPlayerService.PLAY_CONTINUE);
		filter.addAction(MusicPlayerService.ERROR);
		registerReceiver(mPlayerEvtReceiver, filter);
	}

}
